package com.party.core.service.crowdfund.biz;

import com.google.common.collect.Maps;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.*;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: yangshoukun
 * @Date: 2018/6/13 16:09
 */
@Service
public class ProjectDetailCountBizService {

    @Autowired
    private IProjectDetailCountService projectDetailCountService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    /**
     * 通过众筹id 和 创建日期插入或者获取数据
     * @param projectId
     * @param createDate
     * @return
     */
    public ProjectDetailCount getSet(String projectId, Date createDate) {
        if (StringUtils.isEmpty(projectId) || null == createDate) {
            return null;
        }
        ProjectDetailCount projectDetailCount = projectDetailCountService.findByProjectIdDate(projectId, createDate);
        if (null == projectDetailCount || StringUtils.isEmpty(projectDetailCount.getId())) {
            Project project = projectService.get(projectId);
            TargetProject targetProject = targetProjectService.findByProjectId(projectId);
            Activity activity = activityService.get(targetProject.getTargetId());

            projectDetailCount = new ProjectDetailCount();
            projectDetailCount.setEventId(activity.getEventId());
            projectDetailCount.setProjectId(projectId);
            projectDetailCount.setCreateBy(project.getAuthorId());
            projectDetailCount.setUpdateBy(project.getAuthorId());
            projectDetailCount.setCreateDate(createDate);
            projectDetailCount.setMoney(0.0);
            projectDetailCount.setOrderNum(0);
            projectDetailCountService.insert(projectDetailCount);
        }
        return projectDetailCount;
    }

    /**
     * 统计某个众筹某天的数据
     * @param projectId
     * @param createDate
     */
    public void countProjectSomeDay(String projectId, Date createDate) {
        ProjectDetailCount projectDetailCount = getSet(projectId, createDate);
        if (null == projectDetailCount) {
            return;
        }
        Map<String, Object> map = supportService.countByProjectDate(projectId, createDate);
        if (null == map) {
            return;
        }
        Integer orderNum = map.get("orderNum") == null ? 0 : Integer.parseInt(map.get("orderNum").toString());
        BigDecimal money = map.get("money") == null ? new BigDecimal(0) : new BigDecimal(map.get("money").toString());
        projectDetailCount.setOrderNum(orderNum);
        projectDetailCount.setMoney(money.doubleValue());
        projectDetailCount.setUpdateDate(new Date());
        projectDetailCountService.update(projectDetailCount);
    }

    /**
     * 矫正某个众筹的所有数据
     * @param projectId
     */
    public void reviseProject(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return;
        }
        List<ProjectDetailCount> list = supportService.countReviseByProject(projectId);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Project project = projectService.get(projectId);
        TargetProject targetProject = targetProjectService.findByProjectId(projectId);
        Activity activity = activityService.get(targetProject.getTargetId());

        boolean hasOnlyApply = false;

        int orderNum = 0;
        double money = 0;
        Date applyDate = null;

        for (ProjectDetailCount detailCount : list) {
            ProjectDetailCount dbDetailCount = projectDetailCountService.findByProjectIdDate(projectId, detailCount.getCreateDate());
            if (null == dbDetailCount || StringUtils.isEmpty(dbDetailCount.getId())) {
                // 插入
                final String pattern = "yyyy-MM-dd 00:00:00";
                int diffDate;
                try {
                    diffDate = DateUtils.diffDate(
                        DateUtils.parse(DateUtils.formatDate(detailCount.getApplyDate(), pattern), pattern),
                        DateUtils.parse(DateUtils.formatDate(detailCount.getCreateDate(), pattern), pattern)
                    );
                } catch (ParseException e) {
                    e.printStackTrace();
                    diffDate = -1;
                }

                if (diffDate >= 0) {
                    // 报名时间比支持时间大, 只能是转移的情况. 把这些都合并成一个新的报名时间(转移的时间)
                    applyDate = detailCount.getApplyDate();
                    orderNum = orderNum + detailCount.getOrderNum();
                    money = money + detailCount.getMoney();
                } else {
                    detailCount.setCreateDate(detailCount.getCreateDate());
                    detailCount.setEventId(activity.getEventId());
                    detailCount.setProjectId(projectId);
                    detailCount.setCreateBy(project.getAuthorId());
                    detailCount.setUpdateBy(project.getAuthorId());
                    projectDetailCountService.insert(detailCount);

                    // 如果报名当天没有支持, 就加一条报名那天的记录数据
                    if (!hasOnlyApply) {
                        getSet(projectId, detailCount.getApplyDate());
                        hasOnlyApply = true;
                    }
                }
            } else {
                // 修改
                dbDetailCount.setMoney(detailCount.getMoney());
                dbDetailCount.setOrderNum(detailCount.getOrderNum());
                projectDetailCountService.update(dbDetailCount);
            }
        }

        if (null != applyDate) {
            ProjectDetailCount dbDetailCount = projectDetailCountService.findByProjectIdDate(projectId, applyDate);
            if (null == dbDetailCount) {
                ProjectDetailCount projectDetailCount = new ProjectDetailCount();
                projectDetailCount.setEventId(activity.getEventId());
                projectDetailCount.setProjectId(projectId);
                projectDetailCount.setCreateBy(project.getAuthorId());
                projectDetailCount.setUpdateBy(project.getAuthorId());
                projectDetailCount.setCreateDate(applyDate);
                projectDetailCount.setMoney(money);
                projectDetailCount.setOrderNum(orderNum);
                projectDetailCountService.insert(projectDetailCount);
            } else {
                dbDetailCount.setOrderNum(dbDetailCount.getOrderNum() + orderNum);
                dbDetailCount.setMoney(dbDetailCount.getMoney() + money);
                projectDetailCountService.update(dbDetailCount);
            }
        }
    }

    /**
     * 矫正众筹转移后的数据
     * @param fromProjectId
     * @param toProjectId
     */
    public void reviseProjectWhenTransfer(String fromProjectId, String toProjectId) {
        if (StringUtils.isEmpty(fromProjectId) || StringUtils.isEmpty(toProjectId)) {
            return;
        }
        // 将from的统计数据删除
        ProjectDetailCount fromParam = new ProjectDetailCount();
        fromParam.setProjectId(fromProjectId);
        List<ProjectDetailCount> froms = projectDetailCountService.listPage(fromParam, null);
        froms.forEach(fromProject -> projectDetailCountService.delete(fromProject.getId()));

        // 矫正来源
        reviseProject(fromProjectId);
        // 矫正去处
        reviseProject(toProjectId);
    }

    /**
     * 校验所有的还在进行的众筹事件的数据
     */
    public void reviseEvent(String eventId) {
        CrowdfundEvent event = new CrowdfundEvent();
        if (StringUtils.isNotEmpty(eventId)) {
            event.setId(eventId);
        }
        event.setProgress(YesNoStatus.YES.getCode()); // 进行中
        Map<String, Object> params = Maps.newHashMap();
        params.put("openStatus", 1);
        List<CrowdfundEvent> crowdfundEventList = crowdfundEventService.listWithParams(event, params);
        if (CollectionUtils.isEmpty(crowdfundEventList)) {
            return;
        }
        for (CrowdfundEvent crowdfundEvent : crowdfundEventList) {
            List<ProjectWithAuthor> projects = projectService.eventAllList(crowdfundEvent.getId());

            for (ProjectWithAuthor project : projects) {
                reviseProject(project.getId());
            }
        }
    }
}
